<template>
  <div class="ai-container">
    <!-- 头部选择区 -->
    <div class="header-section">
      <el-select
          v-model="modelValue"
          placeholder="选择模型"
          size="default"
          class="model-select"
      >
        <el-option
            v-for="model in models"
            :key="model.value"
            :label="model.label"
            :value="model.value"
        />
      </el-select>
    </div>

    <!-- 对话内容区 -->
    <div class="content-wrapper">
      <div class="content-section">
        <el-scrollbar ref="scrollbarRef" height="calc(100vh - 240px)">
          <div class="messages">
            <div
                v-for="(message, index) in messages"
                :key="index"
                :class="['message-item', message.role]"
            >
              <div class="message-box">
                <div>
                  <el-avatar
                      :size="30"
                      :fit="cover"
                      :src="message.role === 'assistant' ? assistantAvatar : userAvatar"
                      :style="{ border: '2px solid #fff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"
                  />
                </div>
                <div class="message-content">
                  <div class="message-body">
                    <div v-if="!message.loading">
                      <v-md-preview
                          v-if="message.role === 'assistant'"
                          :text="message.content"
                          :preview-options="{
                          markdown: {
                            lineNumbers: true,
                            breaks: true,
                          },
                        }"
                      />
                      <div v-else>{{ message.content }}</div>
                    </div>
                    <div v-else class="loading-dots">
                      <span></span><span></span><span></span>
                    </div>
                  </div>
                  <!-- 操作按钮 -->
                  <div class="message-actions" v-if="!message.loading">
                    <el-button-group>
                      <el-button link size="small" @click="copyMessage(message)"
                      >复制
                      </el-button
                      >
                      <el-button
                          link
                          size="small"
                          @click="retryMessage(message)"
                          v-if="message.role === 'assistant'"
                      >重试
                      </el-button
                      >
                      <el-button link size="small" @click="shareMessage(message)"
                      >分享
                      </el-button
                      >
                    </el-button-group>
                  </div>
                </div>
              </div>
              <!-- 建议按钮 -->
              <div
                  v-if="message.role === 'assistant' && message.suggestions"
                  class="suggestion-buttons"
              >
                <button
                    v-for="(suggestion, idx) in message.suggestions"
                    :key="idx"
                    class="suggestion-button"
                    @click="handleSuggestion(suggestion)"
                >
                  {{ suggestion }}
                </button>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-section-wrapper">
      <div class="input-section">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            :disabled="isLoading"
            placeholder="输入问答内容"
            resize="none"
            @keydown.enter.prevent="handleEnter"
        />
        <div class="input-actions">
          <el-button circle size="small">
            <el-icon>
              <Paperclip/>
            </el-icon>
          </el-button>
          <el-button circle size="small">
            <el-icon>
              <Link/>
            </el-icon>
          </el-button>
          <el-button
              type="primary"
              circle
              :loading="isLoading"
              @click="sendMessage"
          >
            <el-icon>
              <Promotion/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, nextTick, onUnmounted} from "vue";
import {ElMessage} from "element-plus";
import VMdPreview from "@kangc/v-md-editor/lib/preview";
import "@kangc/v-md-editor/lib/style/preview.css";
import githubTheme from "@kangc/v-md-editor/lib/theme/github.js";
import "@kangc/v-md-editor/lib/theme/style/github.css";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import {create_ai} from "@/api/AI";
import {Promotion, Paperclip, Link} from "@element-plus/icons-vue";

// 配置 VMdPreview
VMdPreview.use(githubTheme, {
  Hljs: hljs,
  config: {
    toc: {
      includeLevel: [1, 2, 3],
    },
  },
});

// 基础数据
const scrollbarRef = ref(null);
const assistantAvatar = new URL("@/assets/images/kimi_avatar_share-D0_URDvr.png", import.meta.url)
    .href;
const userAvatar = new URL("@/assets/images/profile.jpg", import.meta.url)
    .href;
const isLoading = ref(false);
const controller = ref(null);

// 模型配置
const models = ref([
  {value: "qwen2.5-3b-instruct", label: "千义普通版本"},
  {value: "qwen-max", label: "千义高级Pro版本"},
  {value: "gpt-4", label: "GPT-4"},
  {value: "gpt-3.5-turbo", label: "GPT-3.5"},
]);

// 状态管理
const modelValue = ref("qwen2.5-3b-instruct");
const inputMessage = ref("");
const messages = ref([
  {
    role: "assistant",
    content: "你好！我是AI助手，很高兴为您服务。请问有什么我可以帮助您的吗？",
    suggestions: [
      "你能帮我查天气吗？",
      "能介绍一下你的功能吗？",
      "你对电影有什么推荐？",
    ],
  },
]);

// 消息操作方法
const copyMessage = (message) => {
  navigator.clipboard.writeText(message.content);
  ElMessage.success("已复制到剪贴板");
};

const retryMessage = (message) => {
  if (message.role === "assistant") {
    const lastUserMessage = messages.value
        .slice()
        .reverse()
        .find((m) => m.role === "user");
    if (lastUserMessage) {
      sendMessage(lastUserMessage.content);
    }
  }
};

const shareMessage = (message) => {
  ElMessage.info("分享功能开发中");
};

const handleSuggestion = (suggestion) => {
  inputMessage.value = suggestion;
  sendMessage();
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (scrollbarRef.value) {
    scrollbarRef.value.setScrollTop(scrollbarRef.value.wrapRef.scrollHeight);
  }
};

// 处理回车事件
const handleEnter = (e) => {
  if (e.shiftKey) return; // Shift + Enter 换行
  sendMessage();
};

// 发送消息
const sendMessage = async (content = null) => {
  const userInput = inputMessage.value.trim();
  if (!userInput || isLoading.value) return;

  try {
    isLoading.value = true;
    controller.value = new AbortController();

    // 添加用户消息
    messages.value.push({
      role: "user",
      content: userInput,
    });

    if (!content) {
      inputMessage.value = "";
    }
    await scrollToBottom();

    // 添加AI思考状态
    const loadingMessage = {
      role: "assistant",
      content: "思考中...",
      loading: true,
    };
    messages.value.push(loadingMessage);
    await scrollToBottom();

    // 发送请求
    const response = await create_ai({
      model: modelValue.value,
      message: userInput,
      signal: controller.value.signal,
    });

    // 更新消息
    const messageIndex = messages.value.indexOf(loadingMessage);
    if (messageIndex !== -1) {
      messages.value.splice(messageIndex, 1, {
        role: "assistant",
        content: response.data,
        suggestions: ["继续", "换个话题", "能详细解释一下吗？"],
      });
    }

    await scrollToBottom();
  } catch (error) {
    // 错误处理
    const messageIndex = messages.value.findIndex((m) => m.loading);
    if (messageIndex !== -1) {
      messages.value.splice(messageIndex, 1);
    }

    if (error.name === "AbortError" || error.message === "请求已取消") return;

    messages.value.push({
      role: "assistant",
      content: "抱歉，处理您的请求时出现错误，请重试。",
    });

    ElMessage.error("发送消息失败，请重试");
    console.error("发送消息失败:", error);
  } finally {
    isLoading.value = false;
    controller.value = null;
  }
};

// 组件卸载时清理
onUnmounted(() => {
  if (controller.value) {
    controller.value.abort();
  }
});
</script>

<style scoped>
.ai-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-section {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
  background-color: var(--el-bg-color);
  border-bottom: 2px solid var(--el-border-color-lighter);
}

.model-select {
  width: 200px;
}

.content-wrapper {
  flex: 1;
  margin: 0 auto;
  width: 100%;
}

.content-section {
  margin-bottom: 80px;
}

.messages {
  padding: 0 10px;
  max-width: 900px;
  margin: 0 auto;

}

/* 消息布局样式 */
.message-item {
  margin-bottom: 24px;
  padding: 0 20px;

}

.message-box {
  display: flex;
  gap: 15px;
  align-items: flex-start;
}

.message-item.user .message-box {
  flex-direction: row-reverse;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.message-body {
  padding: 7px 15px;
  background: transparent; /* 移除背景色 */
  border-radius: 0; /* 移除圆角 */
  position: relative;
  word-break: break-word;
  white-space: pre-wrap;
  box-shadow: none; /* 移除阴影 */
  color: var(--el-text-color-primary); /* 使用主题文字颜色 */
}

.message-item.user .message-body {
  background: #65a0f3; /* 更柔和的背景色 */
  color: #ffffff; /* 更深的文字颜色 */
  border-radius: 12px; /* 圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 操作按钮样式 */
.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-item:hover .message-actions {
  opacity: 1;
}

/* 建议按钮样式 */
.suggestion-buttons {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.suggestion-button {
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 8px 12px;
  text-align: left;
  transition: all 0.3s;
  cursor: pointer;
}

.suggestion-button:hover {
  background: var(--el-fill-color);
  border-color: var(--el-border-color);
}

/* 加载动画 */
.loading-dots {
  display: flex;
  gap: 4px;
  padding: 8px;
  justify-content: center;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--el-text-color-secondary);
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 输入区域 */
.input-section-wrapper {
  position: fixed;
  bottom: 0;
  left: 55%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 1200px;
  padding: 16px 24px;
  background-color: var(--el-bg-color);
  z-index: 100;
}

.input-section {
  display: flex;
  align-items: center;
  gap: 12px;
  border: 1px solid #e0e0e0; /* 浅灰色边框 */
  background-color: #ffffff; /* 白色背景 */
  border-radius: 12px;
  padding: 12px 16px;
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.input-section .el-input {
  flex: 1;
}

.input-section .el-input :deep(.el-textarea__inner) {
  border: none;
  background: transparent;
  box-shadow: none !important;
  padding: 4px 0;
  min-height: 20px !important;
  line-height: 1.5;
  font-size: 14px;
  resize: none;
}

.input-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* Markdown 样式 */
.message-body :deep(.github-markdown-body) {
  background: transparent;
  padding: 0;
  margin: 0;
  font-size: 14px;
  color: inherit;
}

.message-body :deep(pre) {
  background: var(--el-fill-color-light);
  border-radius: 4px;
  padding: 12px;
  margin: 8px 0;
}

.message-body :deep(code) {
  font-family: "Fira Code", monospace;
  font-size: 13px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .ai-container {
    padding: 0;
  }

  .header-section {
    padding: 8px 12px;
  }

  .messages {
    padding: 0 12px;
  }

  .message-item {
    padding: 0 12px;
  }

  .input-section-wrapper {
    position: fixed;
    bottom: 0;
    left: 50%;
    padding: 16px 24px; /* 增加内边距 */
    transform: translateX(-50%);
    width: 100%;
    max-width: 1200px;
    padding: 16px 24px;
    margin-top: 1px; /* 居中 */
    background-color: var(--el-bg-color);
    border-top: 3px solid var(--el-border-color-lighter);
    z-index: 100;
  }

  .input-section {
    display: flex;
    align-items: center;
    gap: 12px;
    background-color: var(--el-fill-color-light);
    border-radius: 12px;
    padding: 12px 16px;
    max-width: 800px;
    margin: 0 auto;
    border: none; /* 移除容器边框 */
    box-shadow: none; /* 移除容器阴影 */
  }

  .model-select {
    width: 150px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .message-body :deep(pre) {
    background: var(--el-bg-color-overlay);
  }

  .message-body :deep(code) {
    color: var(--el-text-color-primary);
  }

  .message-item.user .message-body {
    background: var(--el-color-primary-dark-2);
  }

  .suggestion-button {
    background: var(--el-bg-color);
  }
}

/* 滚动条美化 */
.content-section :deep(.el-scrollbar__bar) {
  opacity: 0.3;
}

.content-section :deep(.el-scrollbar__bar):hover {
  opacity: 0.8;
}

/* 输入框焦点状态 */
.input-section .el-input :deep(.el-textarea__inner):focus {
  border: none; /* 移除输入框边框 */
  background: transparent;
  box-shadow: none !important; /* 移除输入框阴影 */
  padding: 4px 0;
  min-height: 20px !important;
  line-height: 1.5;
  font-size: 14px;
  resize: none;
}
</style>